package com.example.pong;

import android.graphics.Canvas;
import sheep.game.Layer;
import sheep.graphics.Image;
import sheep.math.BoundingBox;

public class GameLayer extends Layer {
	
	private Level level;
	private Ball ball;
	private Player player;
	private Computer computer;
	private Score score;
	
	public GameLayer(int width, int height){
		level = new Level(width, height);
		ball = new Ball(new Image(R.drawable.ball));
		player = new Player(new Image(R.drawable.racket));
		computer = new Computer(new Image(R.drawable.racket));
		score = new Score();
		
		reset();
	}

	@Override
	public void update(float dt) {
		ball.update(dt);
		player.update(dt);
		computer.update(dt);
		
		computer.update(ball.getPosition());
		
		//Racket logic
		if(player.collides(ball)) ball.setSpeed(ball.getSpeed().getX(), -ball.getSpeed().getY());
		if(computer.collides(ball)) ball.setSpeed(ball.getSpeed().getX(), -ball.getSpeed().getY());
		
		//Wall logic
		if(ball.getPosition().getX()<20||ball.getPosition().getX()>level.getWidth()-20){
			ball.setSpeed(-ball.getSpeed().getX(), ball.getSpeed().getY());
		}
		
		//Score logic
		if(ball.getPosition().getY()>=level.getHeight()){
			score.setComputerScore();
			reset();
		}
		if(ball.getPosition().getY()<=0) {
			score.setPlayerScore();
			reset();
		}
	}

	@Override
	public void draw(Canvas canvas, BoundingBox box) {
		level.draw(canvas);
		ball.draw(canvas);
		player.draw(canvas);
		computer.draw(canvas);
		score.draw(canvas);
	}

	public void reset(){
		ball.setPosition(level.getWidth()/2, level.getHeight()/2);
		ball.setSpeed(-440, 150);
		player.setPosition(level.getWidth()/2, level.getHeight()-80);
		computer.setPosition(level.getWidth()/2, 40);
		player.stopPlayer();
	}

	public Player getPlayer() {
		return player;
	}
}
